// pages/home/home.js
import {
  getViewPager,
  getCourseRecommend,
  getInstituteRecommend,
  getCertificateRecommend,
} from '../../api/recommend.js';

import {login} from '../../api/user'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    isIOS: false,
    px2rpx: 1,
    index: 0,
    scrollY: false,
    viewPager: [],
    navList: [{
      icon: '/resource/images/icon_nav_course_options.png',
      text: '课程分类',
      url: '/pages/home/course/options'
    },{
      icon: '/resource/images/icon_nav_college.png',
      text: '企业学堂',
      url: '/pages/institute/list/list'
    },  {
      icon: '/resource/images/icon_nav_talent.png',
      text: '院校人才',
      url: '/pages/talent/list'
    },  {
      icon: '/resource/images/icon_nav_activity.png',
      text: '线下活动',
      url: '/pages/activity/list/list'
    }, {
      icon: '/resource/images/icon_nav_certificate.png',
      text: '人才库申请',
      url: '/pages/credentials/list/list'
    },{
      icon: '/resource/images/icon_nav_course_master.png',
      text: '大咖聊聊',
      url: '/pages/home/course/list?type=2'
    },
    // {
    //   icon: '/resource/images/icon_nav_course_free.png',
    //   text: '免费课程',
    //   url: '/pages/home/course/list?type=1'
    // }
  ],
    courseList: [],
    instituteList: [],
    masterList: [],
    certificateList: [],
    coursePageNo: 1,
    institutePageNo: 1,
    masterPageNo: 1,
    certificatePageNo: 1,
    courseRowCount: 0,
    instituteRowCount: 0,
    masterRowCount: 0,
    certificateRowCount: 0,
    roleId:0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showLoading()
    this.setData({
      isIOS: getApp().globalData.isIOS,
    })
    this.login();
    this.loadCourseRecommend(0);
    this.loadInstituteRecommend();
    this.loadCourseRecommend(1);
    this.loadCertificateRecommend();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.data.px2rpx = getApp().globalData.systemInfo.px2rpx;
    this.loadViewPagerData();
    this.setData({
      roleId:getApp().globalData.roleId
    })
  },

  /**
   * 滑动距离
   * @param {object} e 
   */
  onPageScroll(e) {
    // 拖动到一定的高度，才允许推荐模块自己滚动
    if (e.scrollTop * this.data.px2rpx >= 460 && !this.data.scrollY) {
      this.setData({
        scrollY: true
      })
    } else if (e.scrollTop * this.data.px2rpx < 460 && this.data.scrollY) {
      this.setData({
        scrollY: false
      })
    }
  },

  /**
   * 加载轮播图数据
   */
  loadViewPagerData() {
    getViewPager().then(res => {
      this.setData({
        viewPager: res
      })
    })
  },

  /**
   * 加载课程/大咖推荐数据
   * @param {number} type 0-课程推荐 1-大咖推荐
   */
  loadCourseRecommend(type) {
    getCourseRecommend(type, type === 0 ? this.data.coursePageNo : this.data.masterPageNo).then(res => {
      if (type === 0) {
        this.setData({
          courseList: this.data.courseList.concat(res.list),
          courseRowCount: res.rowCount
        })
      } else {
        this.setData({
          masterList: this.data.masterList.concat(res.list),
          masterRowCount: res.rowCount
        })
      }
    })
  },

  /**
   * 加载商学院推荐数据
   */
  loadInstituteRecommend() {
    getInstituteRecommend(this.data.institutePageNo).then(res => {
      this.setData({
        instituteList: this.data.instituteList.concat(res.list),
        instituteRowCount: res.rowCount
      })
    })
  },

  /**
   * 加载证书推荐数据
   */
  loadCertificateRecommend() {
    getCertificateRecommend(this.data.certificatePageNo).then(res => {
      this.setData({
        certificateList: this.data.certificateList.concat(res.list),
        certificateRowCount: res.rowCount
      })
    })
  },

  /**
   * 轮播图跳转
   * @param {object} e 
   */
  handleNavigatorToViewPager(e) {
    const {
      id,
      type
    } = e.currentTarget.dataset;
    let url = '';
    if (type === 0) { // 课程
      url = `/pages/learn/course/details?id=${id}`
    } else if (type === 1) { // 直播
      url = `/pages/live/live?id=${id}`
    } else if (type === 2) { // 证书
      url = `/pages/credentials/detail/detail?id=${id}`
    } else if (type === 3) { // 活动
      url = `/pages/activity/details/details?id=${id}`
    } else if (type === 4) { // 文章
      url = `/pages/home/article/index?id=${id}`
    }
    wx.navigateTo({
      url: url,
    })
  },

  /**
   * 分类跳转
   * @param {object} e 
   */
  handleNavigatorToNav(e) {
    console.log(e.currentTarget.dataset.url)
    console.log("roleid",this.data.roleId)
    if(e.currentTarget.dataset.url=='/pages/talent/list'){
      if(this.data.roleId==1){
        wx.navigateTo({
          url: e.currentTarget.dataset.url
        })
      }else{
        wx.showToast({
          title: '您没有相关权限',
          icon:'none',
          duration: 2000
        })
      }
    }else if(e.currentTarget.dataset.url=='/pages/institute/list/list'){
      if(this.data.roleId ==1 || this.data.roleId ==4){
        wx.navigateTo({
          url: e.currentTarget.dataset.url
        })
      }else{
        wx.showToast({
          title: '您没有相关权限',
          icon:'none',
          duration: 2000
        })
      }
    }else{
      wx.navigateTo({
        url: e.currentTarget.dataset.url
      })
    }
  },

  /**
   * tabs 切换
   */
  handleTabsChange(e) {
    const {
      key
    } = e.detail;
    const index = parseInt(key);
    this.setData({
      key,
      index,
    })

    // tab 选中切换，即重新加载数据
    if (index === 0) { // 课程推荐
      this.data.coursePageNo = 1;
      this.data.courseList.length = 0;
      this.loadCourseRecommend(0);
    } else if (index === 1) { // 商学院推荐
      this.data.institutePageNo = 1;
      this.data.instituteList.length = 0;
      this.loadInstituteRecommend();
    } else if (index === 2) { // 大咖推荐
      this.data.masterPageNo = 1;
      this.data.masterList.length = 0;
      this.loadCourseRecommend(1);
    } else if (index === 3) { // 证书推荐
      this.data.certificatePageNo = 1;
      this.data.certificateList.length = 0;
      this.loadCertificateRecommend();
    }

  },

  /**
   * swiper 切换
   */
  handleSwiperChange(e) {
    const {
      current
    } = e.detail;
    const key = current.toString();
    this.setData({
      key,
      index: current,
    })
  },

  /**
   * 滚动到底部
   * @param {object} e 
   */
  handleScrollBottom(e) {
    const {
      index
    } = e.currentTarget.dataset;
    if (index === 0 && this.data.courseRowCount > this.data.courseList.length) { // 课程推荐
      this.data.coursePageNo += 1;
      this.loadCourseRecommend(0);
    } else if (index === 1 && this.data.instituteRowCount > this.data.instituteList.length) { // 商学院推荐
      this.data.institutePageNo += 1;
      this.loadInstituteRecommend();
    } else if (index === 2 && this.data.masterRowCount > this.data.masterList.length) { // 大咖推荐
      this.data.masterPageNo += 1;
      this.loadCourseRecommend(1);
    } else if (index === 3 && this.data.certificateRowCount > this.data.certificateList.length) { // 证书推荐
      this.data.certificatePageNo += 1;
      this.loadCertificateRecommend();
    }
  },

  /**
   * 跳转课程详情
   * @param {object} e 
   */
  navigatorCourse(e) {
    wx.navigateTo({
      url: '/pages/learn/course/details?id=' + e.detail,
    })
  },

  /**
   * 跳转商学院详情
   * @param {object} e 
   */
  navigatorInstitute(e) {
    if (getApp().globalData.userInfo.vip) {
      wx.navigateTo({
        url: '/pages/institute/details/details?id=' + e.currentTarget.dataset.id,
      })
    } else {
      wx.showToast({
        title: '成为会员才可查看商学院详情',
        icon: 'none',
      })
    }
  },

  /**
   * 跳转证书详情
   * @param {object} e 
   */
  navigatorCertificate(e) {
    wx.navigateTo({
      url: '/pages/credentials/detail/detail?id=' + e.currentTarget.dataset.id,
    })
  },

  login(){
    //首页登录获取roleId
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          // 静默登录
          wx.login({
            success: res => {
              let code = res.code;

              wx.getUserInfo({
                success: res => {
                   console.log( '用户信息info',res)
                  // 可以将 res 发送给后台解码出 unionId
                  //this.globalData.userInfo = res.userInfo
                  
                  // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
                  // 所以此处加入 callback 以防止这种情况
                  if (this.userInfoReadyCallback) {
                    this.userInfoReadyCallback(res)
                  }
                  // 静默登录
                  login({
                    code,
                    iv: res.iv,
                    encryptedData: res.encryptedData
                  }).then(res => {
                    this.setData({
                      roleId:res.roleId
                    })
                    wx.hideLoading()
                  }).then(res => {
                    wx.hideLoading()
                    //this.globalData.unRead = res;
                  }).catch(err => {
                    wx.hideLoading()
                    //this.globalData.isLogin = false;
                  })
                }
              })
            }
          })
        }else{
          wx.hideLoading()
        }
      },
      fail: error=>{
        wx.hideLoading()
      }
    }
    )
  }

})